package vn.gq.tym.scr;

import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;

import vn.gq.tym.comictemplate.Bookmark;
import vn.gq.tym.comictemplate.R;
import vn.gq.tym.comictemplate.ReaderActivity;
import vn.gq.tym.model.CategoryAdapter;
import vn.gq.tym.model.item.ChapterItem;
import vn.gq.tym.utils.Client;
import vn.gq.tym.utils.DataType;
import vn.gq.tym.utils.DialogHelper;
import vn.gq.tym.utils.IClientListener;
import vn.gq.tym.utils.IDialogHelper;
import android.R.integer;
import android.graphics.Typeface;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuInflater;
import com.actionbarsherlock.view.MenuItem;

public class CategoryScr extends BaseFragment implements OnItemClickListener {

	private ListView mListView;
	private CategoryAdapter mAdapter;
	private ProgressBar mProgressBar;
	private boolean sorted = false;
	
	public static CategoryScr newInstance(String url) {
		CategoryScr f = new CategoryScr();
		Bundle args = new Bundle();
		args.putString("URL", url);
		f.setArguments(args);
		return f;
	}
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setHasOptionsMenu(true);
		setRetainInstance(true);
	}

	@Override
	public void onResume() {
		super.onResume();
		if (mAdapter != null) {
			mAdapter.notifyDataSetChanged();
		}
	}

	@Override
	protected int getLayoutId() {
		return R.layout.fragment_category;
	}

	@Override
	protected int getContainerId() {
		return 0;
	}

	@Override
	protected void createView() {
		mListView = (ListView) findViewById(R.id.list);
		mListView.setOnItemClickListener(this);
		mProgressBar = (ProgressBar) findViewById(R.id.loading);
		mAdapter = new CategoryAdapter(getActivity(), this);
		mAdapter.load(getArguments().getString("URL"), new Runnable() {
			
			@Override
			public void run() {
				mListView.setAdapter(mAdapter);
				mProgressBar.setVisibility(View.GONE);
				
				loadBookmark();
				
			}
		});
		Typeface tf = Typeface.createFromAsset(getActivity().getAssets(), "fonts/Roboto-Condensed.ttf");
		TextView notification = (TextView) findViewById(R.id.notiTextView);
		notification.setTypeface(tf);
		notification.setSelected(true);
	}
	
	public void loadBookmark() {
		final ChapterItem chapterItem = Bookmark.loadChapter(getActivity());
		if (chapterItem != null) {
			final int position = Bookmark.getLastPosition(getActivity());
			DialogHelper.showConfirm(getActivity(), String.format("Nhấn \"Có\" để đọc tiếp %s, trang %d", chapterItem.getName(), position + 1), new IDialogHelper() {
				
				@Override
				public void onOk() {
					loadChapterForDetail(chapterItem, position);
				}
				
				@Override
				public void onCancel() {
					
				}
			}, true);
		}
	}

	@Override
	public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
		inflater.inflate(R.menu.cat, menu);
		super.onCreateOptionsMenu(menu, inflater);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch(item.getItemId()) {
			case R.id.menu_sort:
				mAdapter.onSort();
				sorted = !sorted;
				break;
		}
		return super.onOptionsItemSelected(item);
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		if (id > -1) {
			final ChapterItem chapterItem = (ChapterItem) mAdapter.getItem(position);
			mAdapter.setSelectedPos(position);
			loadChapterForDetail(chapterItem, 0);
		}
	}
	
	public String getURLPath(String path) {
		if (path.startsWith("http") || path.startsWith("asset://")) return path;
		return String.format("asset://gzip:files/%s", path);
	}
	
	private boolean loading = false;
	
	public void loadChapterForDetail(final ChapterItem chapterItem, final int position) {
		if (!loading) {
			loading = true;
			Bookmark.saveChapter(getActivity(), chapterItem);
			Client client = new Client(getActivity());
			client.setOutputDataType(DataType.GZIP_CIPHER_JSON);
			client.executeAndListener(getURLPath(chapterItem.getChapId()), new IClientListener() {
				
				@Override
				public void onDone(int code, Object result) {
					loading = false;
					if (result != null && result instanceof JSONArray) {
						ArrayList<String> imageList = new ArrayList<String>();
						int n = ((JSONArray) result).length();
						for (int i=0;i<n;i++) {
							String url;
							try {
								url = ((JSONArray) result).getString(i);
								imageList.add(url);
							} catch (JSONException e) {
								e.printStackTrace();
							}
						}
						ReaderActivity.startActivity(getActivity(), imageList, position);
					}
				}
			});
		}
	}
	
	
}
